<template>
    <div>
        <el-col>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    >新增</el-button
                    >
                </el-col>
                </el-row>
                <el-form :model="form" ref="form">
                <el-table v-loading="loading" :data="pricingList">
                    <el-table-column label="序号" align="center" width="80">
                        <template slot-scope="scope">
                            <span>{{
                            (queryParams.pageNum - 1) * queryParams.pageSize +
                            scope.$index +
                            1
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="印数" align="center" class-name="text-center">
                        <template slot-scope="scope">
                            <el-form-item align="center">
                                <template>
                                    <el-input
                                        class="custom-input"
                                        maxlength="5"
                                        v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                                        v-model="form.printerCount"
                                        placeholder="请输入印数"
                                        @change="validatePrinterCount"
                                    ></el-input>
                                    <span v-else>{{ scope.row.printerCount }}</span>
                                </template>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="总价(元)" align="center" >
                        <template slot-scope="scope">
                            <span v-if="!isEdit">{{ scope.row.totalPrice }}</span>
                            <span v-else>{{ totalPrice }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价(元)" align="center" class-name="text-center">
                        <template slot-scope="scope">
                            <el-form-item align="center">
                                <template>
                                    <el-input
                                        class="custom-input"
                                        maxlength="5"
                                        v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                                        v-model="form.unitPrice"
                                        placeholder="请输入单价"
                                        @change="validateUnitPrice"
                                    ></el-input>
                                    <span v-else>{{ scope.row.unitPrice }}</span>
                                </template>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column
                    label="操作"
                    align="center"
                    width="150"
                    class-name="small-padding fixed-width"
                    >
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-if="scope.row.id && !isEdit"
                        >删除</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-check"
                        @click="editForm(scope.row)"
                        v-if="!isEdit"
                        >编辑</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-check"
                        @click="submitForm"
                        v-if="isEdit && (scope.row.id==rowid || !scope.row.id)"
                        >保存</el-button
                        >
                        <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-close"
                        @click="handleCancel(scope.row)"
                        v-if="!scope.row.id || (isEdit && scope.row.id==rowid)"
                        >取消</el-button
                        >
                    </template>
                    </el-table-column>
                </el-table>
                </el-form>
        </el-col>
    </div>
</template>
<script>

import {
  listPrintersPricing,
  addPricing,
  updatePricing,
  delPricing,
} from "@/api/base/digitalPrinters";

export default {
    props:{
        printerId: String,
        parentId: String,
    },
    data() {
        return {
            //加载状态
            loading: true,
            //是否可编辑
            isEdit: false,
            rowid: '',
            total:0,
            //价格列表数据
            pricingList: [],
            

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            }, 
            form: {
                printerCount: '',
                unitPrice: '',
            },
            rules:{
                printerCount: [
                    { required: true, message: '请输入印数', trigger: 'blur' },
                    { validator: this.validatePrinterCount, trigger: ['change', 'blur'] }
                ],
                unitPrice: [
                    { required: true, message: '请输入单价', trigger: 'blur' },
                    { validator: this.validateUnitPrice, trigger: ['change', 'blur'] }
                ]
            }
        }
    },

    created() {
        this.getList();
    },
    computed:{
        totalPrice(){
            const count = Number(this.form.printerCount) || 0
            const price = Number(this.form.unitPrice) || 0
            return (count * price).toFixed(2) // 保留两位小数
        }
    },
    methods: {
        //新增一行
        handleAdd(){
            if(this.isEdit){
                this.$modal.msgError("当前有正在编辑的数据, 请先保存后再新增");
                return
            }
            this.isEdit = true
            // 初始化form
            this.resetForm();

            this.pricingList.push({ printerCount: '', unitPrice: ''});
        },
        //重置表单数据
        resetForm(){
            this.form = {
                printerCount: '',
                unitPrice: '',
            }
        },

        async getList(){
            try{
                this.loading = true
                this.queryParams = {
                    ...this.queryParams,
                    printerId: this.printerId,
                    colorId: this.parentId,
                }
                const res = await listPrintersPricing(this.queryParams);
                if(res && res.code===200){
                    this.pricingList = res.rows
                    this.total = res.total
                }
            }catch(error){
                console.log('查询印价列表出错',error)
            }finally{
                this.loading = false
            }
        },
        //删除
        handleDelete(row){
            this.$modal
                .confirm('是否确定删除信息？删除后数据将无法恢复，请谨慎操作')
                .then(function () {
                    return delPricing(row.id);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});

        },
        editForm(row){
            this.isEdit = !this.isEdit
            this.rowid = row.id
            this.form = {
                ...this.form,
                id: row.id,
                printerCount: row.printerCount,
                unitPrice: row.unitPrice,
                printerId: this.printerId,
                colorId: this.parentId,
            }
        },
        //保存
        async submitForm(){
            console.log(1111111111111111111111)
            // 手动触发校验
            const valid = await this.$refs.form.validate();
            if (!valid) return;
            return;
            try{
                this.form = {
                    ...this.form,
                    printerId: this.printerId,
                    colorId: this.parentId,

                }
                let res = null;
                if(this.isEdit && this.rowid){//说明是编辑保存
                    res = await updatePricing(this.form)
                }else{//说明是新增保存
                    res = await addPricing(this.form)
                }
                if(res && res.code===200){
                    this.$modal.msgSuccess("保存成功");
                    this.getList()
                }
            }catch(error){
                console.log('保存数据出错',error)
            }finally{
                this.isEdit = false
                this.rowid = ''
            }
            
        },
        //取消
        handleCancel(row){
            const id = row.id
            this.isEdit = false
            this.rowid = ''
            if(!id){//删除行
                this.pricingList.splice(this.pricingList.length - 1, 1);
            }
        },
        // 印数校验函数
        validatePrinterCountFn(rule, value, callback) {
            this.validatePrinterCount(value)
                .then(() => callback())
                .catch(err => callback(new Error(err)));
        },
        
        // 单价校验函数
        validateUnitPriceFn(rule, value, callback) {
            this.validateUnitPrice(value)
                .then(() => callback())
                .catch(err => callback(new Error(err)));
        },
        
        // 印数校验逻辑
        async validatePrinterCount(value) {
            if (!value) {
                throw new Error('请输入印数');
            }
            
            const num = Number(value);
            if (!Number.isInteger(num) || num < 1 || num > 9999) {
                throw new Error('请输入1-9999的整数');
            }
            
            const isDuplicate = this.pricingList.some(item => {
                if (this.rowid && item.id === this.rowid) return false;
                return Number(item.printerCount) === num;
            });
            
            if (isDuplicate) {
                throw new Error('该印数已存在');
            }
        },
        
        // 单价校验逻辑
        async validateUnitPrice(value) {
            if (!value) {
                throw new Error('请输入单价');
            }
            
            const num = Number(value);
            if (isNaN(num) || num < 0 || num > 99999) {
                throw new Error('请输入0-99999的数字');
            }
            
            const decimalPart = value.toString().split('.')[1];
            if (decimalPart && decimalPart.length > 4) {
                throw new Error('最多保留4位小数');
            }
        },
        
        // 手动触发校验
        async validateCurrentInput() {
            try {
                await this.validatePrinterCount(this.form.printerCount);
                await this.validateUnitPrice(this.form.unitPrice);
                return true;
            } catch (error) {
                this.$modal.msgError(error.message);
                return false;
            }
        },
    }
}
</script>
<style lang="scss" scoped>
    .custom-input {
        width: 50%;  /* 设置输入框宽度 */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .unit-text {
        font-size: 14px;
        color: #606266;
        margin-left: 5px;  /* 设置“毫米”文本的左边距 */
        margin-right: 5px; 
    }
    ::v-deep .text-center {
        .cell {
            display: flex;
            justify-content: center;
            align-items: center;
            vertical-align: middle;
            text-align: center;
        }
    }
</style>